const fs = require('fs');
const path = require('path');
const readline = require('readline');
const moment = require('moment');

const filePath = path.resolve('./data/record.txt');

// 在最后追加写入一行
function writeLine(line) {
  return fs.appendFileSync(filePath, `${moment().format('YYYY-M-DD HH:mm:ss')} ${line}\r\n`);
}

// 读取最后一行
async function readLastLine() {
  const fileStream = fs.createReadStream(filePath);
  const rl = readline.createInterface({
    input: fileStream,
  });
  let lastLine = '';
  for await (const line of rl) {
    lastLine = line;
  }
  return lastLine;
}

function readFile() {
  return fs.readFileSync(filePath).toString();
}

module.exports = {
  writeLine,
  readFile,
  readLastLine,
};
